import time
from bs4 import BeautifulSoup
from selenium import webdriver
import requests
from common.logger import hslogger
from common.ua import useragent_random
from dao.BaseRepository import BaseRepository
from main import readfile

had_games = readfile()
# browser = webdriver.Chrome()
browser = webdriver.Firefox()
hsgame_dao = BaseRepository(collectionname="hsgame_20200303")

session = requests.session()
# session.headers[
#     "Accept"] = r"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
# session.headers["Accept-Encoding"] = r"gzip, deflate, br"
# session["Host"] = "pan.baidu.com"
# session["User-Agent"] = useragent_random()
# session["Upgrade-Insecure-Request"] = 1
# session["Sec-Fetch-User"] = "?1"
# session["Sec-Fetch-Site"] = "same-origin"
# session["Sec-Fetch-Mode"] = "navigate"
# session["Referer"] = "https://pan.baidu.com/"
content = session.get("https://pan.baidu.com/?adapt=pc&fr=ftw")


# print(content.content)
# html = BeautifulSoup(content.content, 'html5lib')
# a = html.find_all('#login-header > span > a')
# print(len(a))


def main():
    # result, num, msg = hsgame_dao.get_all_no_page(sort=[("modifyTime", -1)])
    result, num, msg = hsgame_dao.get_all_no_page(sort=[("name", 1)])
    for r in result:
        print(r.get("name"))
        # print(r.get("downloadUrl"))



    # 声明浏览器
    # browser.get(url)
    #
    # time.sleep(1)
    # # browser.close()  # 关闭浏览器
    #
    # browser.find_element_by_xpath('//*[@id="TANGRAM__PSP_4__footerULoginBtn"]').click()
    # browser.find_element_by_xpath('//*[@id="TANGRAM__PSP_4__userName"]').send_keys("terrydash")
    # time.sleep(1)
    # browser.find_element_by_xpath('//*[@id="TANGRAM__PSP_4__password"]').send_keys("52xuguoxu")
    # browser.get_screenshot_as_file("a.png")
    # browser.find_element_by_xpath('// *[ @ id = "TANGRAM__PSP_4__submit"]').click()
    #
    # r = ""
    # while r.upper() != "Y":
    #     r = input("是否进入，Y OR N:")
    # r = browser.find_element_by_xpath('//*[@id="dialog1"]/div[2]/div/div[2]')
    # if r:
    #     r.click()

    for r in result:
        if "downloadUrl" in r and len(str(r.get("downloadUrl"))) > 0 and str(r.get("downloadUrl")).startswith(
                "https://pan.baidu"):
            r["downloadUrl"] = str(r.get("downloadUrl")).replace("https://pan.baidu.chttps://pan.baidu.com/s",
                                                                 "https://pan.baidu.com/s")
            try:
                baidupan_save(r.get("downloadUrl"), str(r.get("_id")))
                time.sleep(1)
            except Exception as e:
                hslogger.error(e)
                continue


def baidupan_save(url, id=None):
    browser.get(url)
    # c = session.get(url)
    # html = BeautifulSoup(c.content, 'html5lib')
    # print(c.content)
    # a = html.find_all('div.text > a')
    # print(len(a))
    id = str(id).strip()
    try:
        if len(browser.find_elements_by_xpath('//*[@id="share_nofound_des"]')) == 0:
            # browser.find_element_by_xpath('//*[@id="shareqr"]/div[2]/div[2]/div/ul[1]/li[1]/div/span[1]').click()
            # time.sleep(1)
            # browser.find_element_by_xpath('//*[@id="bd-main"]/div/div[1]/div/div[2]/div/div/div[2]/a[1]').click()
            # time.sleep(1)
            # browser.find_element_by_class_name("g-button-blue-large").click()
            # time.sleep(2)
            print(browser.find_element_by_xpath('//*[@id="shareqr"]/div[2]/div[3]/div/div/dd/div[2]/div[1]/a').text)
            if browser.find_element_by_xpath(
                    '//*[@id="shareqr"]/div[2]/div[3]/div/div/dd/div[2]/div[1]/a').text in had_games:
                print("删除id:", id)
                hsgame_dao.delete_one_by_id(id)
    finally:
        pass


if __name__ == "__main__":
    main()
